

import cv2
import numpy as np
global img
global point1, point2
def nothing(x):#忽略
    pass

def Drd(event, x, y, flags, param):
    global img, point1, point2
    img2 = img.copy()#复制代码
    if event == cv2.EVENT_LBUTTONDOWN:  # 左键点击
        point1 = (x, y)
        # cv2.circle(img2, point1, 10, (0, 255, 0), 5)
        # cv2.imshow('image', img2)
    if event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON):  # 按住左键拖曳
        cv2.rectangle(img2, point1, (x, y), (255, 0, 0), 5)#矩形参数
        cv2.imshow('image', img2)
    elif event == cv2.EVENT_LBUTTONUP:  # 左键释放
        point2 = (x, y)#最终坐标
        cv2.rectangle(img2, point1, point2, (255, 0, 0), 5)#矩形参数
        cv2.imshow('image', img2)



def main():
    global img
    img = np.zeros((400, 600, 3), np.uint8)#设置界面的大小
    cv2.namedWindow('image')#命名界面

    # 创建滑动条
    cv2.createTrackbar('R', 'image', 0, 255, nothing)
    cv2.createTrackbar('G', 'image', 0, 255, nothing)
    cv2.createTrackbar('B', 'image', 0, 255, nothing)
    img[:] = 255  # 将黑色面板化为白色面板

    cv2.setMouseCallback('image', Drd)#将Drsd函数与图形界面img相关
    cv2.imshow('image', img)

    while 1:
      k = cv2.waitKey(1) & 0xFF
      if k == 27:
            break
    cv.destroyAllWindows()#清除界面

if __name__ == '__main__':
       main()






